package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.basic.util.AjaxResult;
import cn.itsource.pethome.user.constant.WechatConstant;
import cn.itsource.pethome.user.domain.WechatUser;
import cn.itsource.pethome.user.domain.dto.WechatUserDto;
import cn.itsource.pethome.user.service.IWechatService;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @description: 描述:
 * @date: 2020/8/17 17:34
 * @author: summer
 * version: 1.0
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;

    /**
     * 转跳到登录界面
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        //获取授权码的url
        String codeUrl = WechatConstant.CODEURL.replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        return "redirect:"+codeUrl;
    }

    /**
     * 功能描述: 回调函数
     * @param code
     * @return: java.lang.String
     * @Date: 2020/8/18
     */
    @RequestMapping("/callback")
    public String callback(String code){
        return "redirect:http://localhost:8081/callback.html?code="+code;
    }

    /**
     * 功能描述: 获取令牌 token
     * @param partm
     * @return: cn.itsource.pethome.basic.util.AjaxResult
     * @Date: 2020/8/18
     */
    @PostMapping("/getToken")
    @ResponseBody
    public AjaxResult getToken(@RequestBody Map<String,String> partm){
        try {
            //获取授权码
            String code = partm.get("code");
            //System.out.println("参数："+code);
            Map<String,Object> map = wechatService.getToken(code);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }

    /**
     * 功能描述: 获取绑定用户界面信息绑定用户
     * @param wechatUserDto
     * @return: cn.itsource.pethome.basic.util.AjaxResult
     * @Date: 2020/8/18
     */
    @PostMapping("/binding")
    @ResponseBody
    public AjaxResult binding(@RequestBody WechatUserDto wechatUserDto){
        try {
            Map<String, Object> map = wechatService.binding(wechatUserDto);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }
}
